package com.ncmmall.api.utils;

import com.ncmmall.application.util.HttpRequests;
import com.feijin.commons.lang.PropertiesHelps;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * 微信工具类
 *
 * @author likaikai
 * @date 2019-07-17 15:15
 */
@Component
@Slf4j
public class WechatUtils {

    @Value("${store.path}")
    private String storePath;

    /**
     * 获取AccessToken
     */
    private String getAccessToken() {

        String appId = PropertiesHelps.getValue("wx.merchant.appid");
        String secret = PropertiesHelps.getValue("wx.merchant.appSecret");

        String result = HttpRequests.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secret);

        JSONObject jsonObject = JSONObject.fromObject(result);

        if (jsonObject.get("errcode") == null || (int) jsonObject.get("errcode") == 0) {
            return (String) jsonObject.get("access_token");
        }

        return "";
    }


    /**
     * 生成小程序码
     */
    public String generateQrcode(String page, String scene) throws Exception {

        String accessToken = getAccessToken();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("scene", scene);
        jsonObject.put("page", page);
        jsonObject.put("width", 280);

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken);

        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
        StringEntity entity = new StringEntity(jsonObject.toString());
        httpPost.setEntity(entity);

        HttpResponse response = httpClient.execute(httpPost);

        InputStream inputStream = response.getEntity().getContent();

        if (response.getEntity().getContentType().getValue().toLowerCase().contains("json")) {

            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder body = new StringBuilder();
            String temp = null;
            while ((temp = reader.readLine()) != null) {
                body.append(temp);
            }
            throw new Exception(body.toString());
        }

        File path = new File(storePath + "/code");
        if (!path.exists()) {
            path.mkdirs();
        }
        String name = System.currentTimeMillis() + ".png";
        FileUtils.copyInputStreamToFile(inputStream, new File(path, name));

        return name;

    }

}
